<template>
  <div class="dialog">
    <el-dialog :title="dialog.title" v-model="dialog.show">
      <div class="form">
        <el-form ref="form" :model="formData" :rules="form_rules" labe-width="120px" style="margin: 10px; width: auto">
          <el-form-item label="姓名:" prop="name" label-width="140px">
            <el-input type="name" v-model="formData.name"></el-input>
          </el-form-item>

          <el-form-item prop="age" label="年龄:" label-width="140px">
            <el-input type="age" v-model="formData.age"></el-input>
          </el-form-item>

          <el-form-item prop="sex" label="性别:" label-width="140px">
            <el-input type="sex" v-model="formData.sex"></el-input>
          </el-form-item>

          <el-form-item prop="position" label="职位:" label-width="140px">
            <el-input type="position" v-model="formData.position"></el-input>
          </el-form-item>

          <el-form-item prop="phone" label="电话:" label-width="140px">
            <el-input type="phone" v-model="formData.phone"></el-input>
          </el-form-item>

          <el-form-item class="text_right" label-width="140px">
            <el-button @click="dialog.show = false">取消</el-button>
            <el-button type="primary" @click="onSubmit(form)">提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, defineEmits } from "vue";
const { proxy } = getCurrentInstance();
const emits = defineEmits(["sendMsg"]);
const props = defineProps({
  dialog: Object,
  formData: Object,
});

const form = ref(null);

const form_rules = reactive({
  name: [{ required: true, message: "姓名不能为空!", trigger: "blur" }],
  age: [{ required: true, message: "年龄不能为空!", trigger: "blur" }],
  sex: [{ required: true, message: "性别不能为空!", trigger: "blur" }],
  position: [{ required: true, message: "职位不能为空!", trigger: "blur" }],
  phone: [{ required: true, message: "电话不能为空!", trigger: "blur" }],
});

const onSubmit = (form) => {
  form.validate((valid) => {
    if (valid) {
      const url =
        props.dialog.option == "add" ? "add" : `edit/${props.formData.id}`;
      proxy.$axios.post(`/nurse/${url}`, props.formData).then((res) => {
        // 编辑成功
        if (props.dialog.option == "edit") {
          proxy.$message({ message: "数据更新成功", type: "success" });
        } else {
          // 添加成功
          proxy.$message({ message: "数据添加成功", type: "success" });
        }
        // 隐藏dialog
        props.dialog.show = false;
        // 数据添加后 需要自己刷新 显然不合理
        // this.$emits('update') vue3 setup语法糖不是这样写
        emits("update");
      });
    }
  });
};
</script>

<style lang="less" scoped></style>
